package main

import (
	"github.com/jinzhu/gorm"
)

var Dba *gorm.DB

func init() {
	db1,err := gorm.Open("mysql","root:123456@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local")
	// 如果设置禁用表名复数形式属性为 true，`User` 的表名将是 `user`
	db1.SingularTable(true)
	if err !=nil {
		panic(err)
	}
	err = db1.DB().Ping()
	if err!=nil {
		db1.Close()
	}
	Dba =db1
}

type  UserOne struct {
   gorm.Model
   Name string
   CreditCards []CreditCard `gorm:"foreignkey:UserRefer"`
}

type Profile struct {
   gorm.Model
    UserOne UserOne `gorm:"association_foreignkey:UserOneRefer"`// 使用 UserRefer 作为外键
	UserRefer string
	Name  string
	CreditCards  []CreditCard `gorm:"foreignkey:UserMemberNumber;association_foreignkey:MemberNumber"`

}
type CreditCard struct {
	gorm.Model
	Number string
	UID       string
	UserRefer  uint
	UserMemberNumber string
}

type oneUser struct {
 gorm.Model
  Languages []*Language `gorm:"many2many:user_languages;"`

}
type Language struct {
	gorm.Model
	Name string
	oneUser  []*oneUser `gorm:"many2many:user_languages;"`

}

func main()  {
 //Has one 一对一的连接，
 var card CreditCard
 var usrerone UserOne
 var oneuser oneUser
 var language Language
 Dba.Model(&usrerone).Related(&card, "CreditCard")
	//// SELECT * FROM credit_cards WHERE user_id = 123; // 123 是用户表的主键
	// CreditCard  是用户表的字段名，这意味着获取用户的信用卡关系并写入变量 card。
	// 像上面的例子，如果字段名和变量类型名一样，它就可以省略， 像：
	Dba.Model(&usrerone).Related(&card)
  //Has Many 一对多
  //Many To Many 多对多 增加中间表

	Dba.Model(&language).Related(&oneuser)
	//// SELECT * FROM "users" INNER JOIN "user_languages" ON "user_languages"."user_id" = "users"."id" WHERE  ("user_languages"."language_id" IN ('111'))
}